"""
简单的测试运行器，不依赖pytest
"""
import sys
import os
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

def run_simple_tests():
    """运行简单测试"""
    print("开始运行简单测试...")
    
    try:
        # 测试导入
        from main import app
        print("[OK] 应用导入成功")
        
        from core.auth import create_access_token, verify_token
        print("[OK] 认证模块导入成功")
        
        from models.user import User
        print("[OK] 用户模型导入成功")
        
        from core.database import SessionLocal
        print("[OK] 数据库模块导入成功")
        
        # 测试token创建和验证
        data = {"sub": "testuser", "user_id": 1}
        token = create_access_token(data)
        print("[OK] Token创建成功")
        
        decoded = verify_token(token)
        print("[OK] Token验证成功")
        
        # 测试数据库连接
        db = SessionLocal()
        try:
            # 执行简单查询
            result = db.execute("SELECT 1").scalar()
            assert result == 1
            print("[OK] 数据库连接成功")
        finally:
            db.close()
        
        print("\n[SUCCESS] 所有基础测试通过！")
        return True
        
    except Exception as e:
        print(f"[ERROR] 测试失败: {e}")
        import traceback
        traceback.print_exc()
        return False

def test_auth_functionality():
    """测试认证功能"""
    print("\n开始测试认证功能...")
    
    try:
        from fastapi.testclient import TestClient
        from main import app
        
        client = TestClient(app)
        
        # 测试根路径
        response = client.get("/")
        assert response.status_code == 200
        print("[OK] 根路径访问成功")
        
        # 测试登录API
        login_data = {
            "username": "admin",
            "password": "admin"
        }
        response = client.post("/api/auth/login", json=login_data)
        if response.status_code == 200:
            print("[OK] 登录API测试成功")
            data = response.json()
            assert "access_token" in data
            assert "refresh_token" in data
            print("[OK] Token返回格式正确")
        else:
            print("[WARN] 登录API测试失败（可能需要初始化数据库）")
        
        print("[OK] 认证功能测试完成")
        return True
        
    except Exception as e:
        print(f"[ERROR] 认证功能测试失败: {e}")
        return False

def main():
    """主函数"""
    print("=" * 50)
    print("大模型信访分析系统 - 简单测试运行器")
    print("=" * 50)
    
    success = True
    
    # 运行基础测试
    if not run_simple_tests():
        success = False
    
    # 运行认证功能测试
    if not test_auth_functionality():
        success = False
    
    print("\n" + "=" * 50)
    if success:
        print("🎉 所有测试通过！系统基础功能正常。")
    else:
        print("❌ 部分测试失败，请检查系统配置。")
        sys.exit(1)
    
    print("=" * 50)

if __name__ == "__main__":
    main()